package www.ld.com.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import www.ld.com.domain.attr.group.pojo.AttrGroupPO;
import www.ld.com.domain.attr.group.query.AttrGroupQuery;
import www.ld.com.domain.attr.group.vo.AttrGroupVO;
import www.ld.com.domain.attr.relation.vo.InRelation;
import www.ld.com.mapper.AttrGroupMapper;

import javax.annotation.Resource;
import java.util.Set;

@Service
public class AttrGroupService {
    @Resource
    private AttrGroupMapper attrGroupMapper;
    @Resource
    private CategoryCacheService categoryCacheService;

    public IPage<AttrGroupVO> pageAttrGroupByAttrGroupQuery(AttrGroupQuery attrGroupQuery) {
        IPage<AttrGroupVO> attrGroupVOIPage = attrGroupMapper.pageAttrGroupByAttrGroupQuery(new Page<>(attrGroupQuery.getCurrent(), attrGroupQuery.getSize()), attrGroupQuery);
        attrGroupVOIPage.getRecords().forEach(v -> {
            v.setCategoryName(categoryCacheService.getCategoryNameById(v.getCategoryId()));
        });
        return attrGroupVOIPage;
    }


    public AttrGroupPO getAttrGroupPOById(String id) {
        return attrGroupMapper.selectById(id);
    }

    @Transactional
    public void saveAttrGroupPO(AttrGroupPO attrGroupPO) {
        attrGroupMapper.insert(attrGroupPO);
    }

    @Transactional
    public void updateAttrGroupPO(AttrGroupPO attrGroupPO) {
        attrGroupMapper.updateById(attrGroupPO);
    }

    @Transactional
    public void deleteAttrGroupById(String id) {
        attrGroupMapper.deleteById(id);
    }

    public Set<String> getRelation(String attrGroupId){
       return attrGroupMapper.findAttrIdByAttrGroupId(attrGroupId);
    }

    @Transactional
    public void relation(InRelation inRelation) {
        if (CollectionUtil.isEmpty(inRelation.getAttrIds())) {
            return;
        }
        final Set<String> attrIdByAttrGroupId = attrGroupMapper.findAttrIdByAttrGroupId(inRelation.getAttrGroupId());
        Set<String> addAttrId = CollectionUtil.newHashSet();
        Set<String> delAttrId = CollectionUtil.newHashSet();
        inRelation.getAttrIds().forEach(v -> {
            if (attrIdByAttrGroupId.contains(v)) {
                delAttrId.add(v);
            } else {
                addAttrId.add(v);
            }
        });
        if (CollectionUtil.isNotEmpty(delAttrId)) {
            attrGroupMapper.delRelation(inRelation.getAttrGroupId(), delAttrId);
        }
        if (CollectionUtil.isNotEmpty(addAttrId)) {
            attrGroupMapper.addRelation(inRelation.getAttrGroupId(), addAttrId);
        }
    }
}
